package com.example.demo.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.AppUtil.*;
import com.example.demo.anno.LoginUser;
import com.example.demo.config.LocalDateTimeFormatConfig;
import com.example.demo.entity.*;
import com.example.demo.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 * @Author:大力王
 * @Date:2024/6/25-25-4:17
 * 开始了
 */
@Api(tags = "会员评论")
@RestController
@RequestMapping("/comment")
public class MemberCommentsController extends BaseActionUtil {
    @Autowired
    private IAfshopCommentService memberCommentsService;
    @Autowired
    private IAfshopCommentPictureService memberCommentsPictureService;
    @Autowired
    private IAfshopCouponService memberCouponService;
    @Resource
    private IAfshopUserCouponService CouponService;
    @Resource
    private LocalDateTimeFormatConfig localDateTimeFormatConfig;
    @Autowired
    private IUserService userService;

    /**
     * 发表评论
     */
    @ApiOperation(value = "发表评论")
    @PostMapping("/post")
    public Object post(@LoginUser User loginUser){
        Map<String, Object> resultObj = new HashMap<>();
        //
        JSONObject jsonParam = getJsonRequest();
        Integer typeId = jsonParam.getInteger("typeId");
        Integer valueId = jsonParam.getInteger("valueId");
        String content = jsonParam.getString("content");
        JSONArray imagesList = jsonParam.getJSONArray("imagesList");
        AfshopComment commentEntity = new AfshopComment();
        commentEntity.setTypeId(typeId);
        commentEntity.setValueId(valueId);
        commentEntity.setContent(content);
        commentEntity.setStatus(0);
        //
        commentEntity.setAddTime(System.currentTimeMillis() / 1000);
        commentEntity.setUserId(loginUser.getUserId());
        commentEntity.setContent(Base64Util.encode(commentEntity.getContent()));
        boolean insertId = memberCommentsService.save(commentEntity);
        AfshopComment comment = memberCommentsService.queryObject(commentEntity.getTypeId());

        if (insertId && null != imagesList && !imagesList.isEmpty()){
            int i = 0;
            for (Object imgLink : imagesList) {
                i++;
                AfshopCommentPicture pictureVo = new AfshopCommentPicture();
                pictureVo.setCommentId(comment.getTypeId());
                pictureVo.setPicUrl(imgLink.toString());
                pictureVo.setSortOrder(i);
                memberCommentsPictureService.save(pictureVo);
            }
        }
        // 是否领取优惠券
        if (insertId && typeId == 0){
            // 当前评价的次数
            Map<String, Object> param = new HashMap<>();
            param.put("valueId", valueId);
            List<AfshopComment> commentVos = memberCommentsService.queryList(param);
            boolean hasComment = false;
            for (AfshopComment commentVo : commentVos) {
                if (commentVo.getUserId().equals(loginUser.getUserId())
                        && !commentVo.getId().equals(insertId)) {
                    hasComment = true;
                }
            }
            if (!hasComment) {
                Map<String, Object> couponParam = new HashMap<>();
                couponParam.put("sendType", 6);
                AfshopCoupon newCouponConfig = memberCouponService.queryMaxUserEnableCoupon(couponParam);
                if (null != newCouponConfig
                        && newCouponConfig.getMinTransmitNum() >= commentVos.size()) {
                    AfshopUserCoupon userCouponVo = new AfshopUserCoupon();
                    userCouponVo.setAddTime(localDateTimeFormatConfig.convertDateToLocalDateTime(new Date()));
                    userCouponVo.setCouponId(newCouponConfig.getId());
                    userCouponVo.setCouponNumber(CharUtil.getRandomString(12));
                    userCouponVo.setUserId(loginUser.getUserId());
                    CouponService.save(userCouponVo);
                    resultObj.put("coupon", newCouponConfig);
                }
            }
        }
        if (insertId) {
            return toResponsObject(0, "评论添加成功", resultObj);
        } else {
            return toResponseFail("评论保存失败");
        }
    }
    @ApiOperation(value = "评论数量")
    @PostMapping("/count")
    public Object count(Integer typeId, Integer valueId) {
        Map<String, Object> resultObj = new HashMap<>();
        //
        Map<String, Object> param = new HashMap<>();
        param.put("typeId", typeId);
        param.put("valueId", valueId);
        Integer allCount = memberCommentsService.queryTotal(param);
        Integer hasPicCount = memberCommentsService.queryhasPicTotal(param);
        //
        resultObj.put("allCount", allCount);
        resultObj.put("hasPicCount", hasPicCount);
        return toResponseSuccess(resultObj);
    }
    @ApiOperation(value = "选择评论类型")
    @PostMapping("/list")
    public Object list(Integer typeId, Integer valueId, Integer showType,
                       @RequestParam(value = "page", defaultValue = "1") Integer page, @RequestParam(value = "size", defaultValue = "10") Integer size,
                       String sort, String order) {
        Map<String, Object> param = new HashMap<>();
        param.put("typeId", typeId);
        param.put("valueId", valueId);
        param.put("page", page);
        param.put("limit", size);
        if (StringUtils.isNullOrEmpty(sort)) {
            param.put("order", "desc");
        } else {
            param.put("order", sort);
        }
        if (StringUtils.isNullOrEmpty(order)) {
            param.put("sidx", "id");
        } else {
            param.put("sidx", order);
        }
        if (null != showType && showType == 1) {
            param.put("hasPic", 1);
        }
        //查询列表数据
        Query query = new Query(param);
        List<AfshopComment> commentList = memberCommentsService.queryList(query);
        int total = memberCommentsService.queryTotal(query);
        ApiPageUtils pageUtil = new ApiPageUtils(commentList, total, query.getLimit(), query.getPage());
        //
        for (AfshopComment commentItem : commentList) {
            commentItem.setContent(Base64Util.decode(commentItem.getContent()));
            commentItem.setUserInfo(userService.queryObject(commentItem.getUserId()));

            Map<String, Object> paramPicture = new HashMap<>();
            paramPicture.put("commentId", commentItem.getId());
            List<AfshopCommentPicture> commentPictureEntities = memberCommentsPictureService.queryList(paramPicture);
            commentItem.setPicList(commentPictureEntities);
        }
        return toResponseSuccess(pageUtil);
    }
}
